package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.Result;
import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.DeviceDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class GreenhouseService extends LogicService<GreenhouseDao, Greenhouse, Long> {

    @Autowired
    private DeviceService deviceService;

    public GreenhouseService(@Autowired GreenhouseDao dao) {
        super(dao);
    }

    public Result addDevice(Long device, Long greenhouse) {
        Device device1 = deviceService.GET(device);
        Greenhouse greenhouse1 = device1.getGreenhouse();
        if (greenhouse1!=null){
            return Result.builder().msg("该设备已绑定大棚").build();
        }

        Greenhouse greenhouse2 = getDAO().getReferenceById(greenhouse);
        Set<Device> devices = greenhouse2.getDevices();
        if(devices.stream().anyMatch(o->o.getDeviceType().equals(device1.getDeviceType()))){
            return Result.builder().msg("类型为[" + device1.getDeviceType() +"]的设备已经绑定该大棚，无法绑定同类型的设备").build();
        }

        Greenhouse gh = getDAO().getReferenceById(greenhouse);
        gh.addDevice(device1);
        getDAO().save(gh);
        return Result.builder().msg("ok").build();
    }

}
